//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.IO.Packaging;
using OpenLS.Core.Serialization;
using OpenLS.Spreadsheet.Serialization;

namespace OpenLS.Spreadsheet
{
    internal class ExternalWorkbook : Workbook, IOfficeXmlSerializable
    {
        private readonly List<ExternalDefinedName> _externalDefinedNames = new List<ExternalDefinedName>();
        private readonly ExternalLink _link;
        private readonly List<ExternalSheetData> _sheetDataSet = new List<ExternalSheetData>();
        private readonly List<ExternalSheetName> _sheetNames = new List<ExternalSheetName>();

        public ExternalWorkbook(ExternalLink l, SpreadsheetDocument document) : base(document)
        {
            _link = l;
        }

        public ExternalLink Link
        {
            get { return _link; }
        }

        internal override string InternalPrefix
        {
            get { return "[" + (Link.Index + 1) + "]"; }
        }

        public List<ExternalSheetName> SheetNames
        {
            get { return _sheetNames; }
        }

        public List<ExternalDefinedName> ExternalDefinedNames
        {
            get { return _externalDefinedNames; }
        }

        public List<ExternalSheetData> SheetDataSet
        {
            get { return _sheetDataSet; }
        }

        #region IOfficeXmlSerializable Members

        void IOfficeXmlSerializable.ReadXml(ReadContext context)
        {
            using (ReadContext c = context.Read("externalBook"))
            {
                SheetNames.AddRange(c.ReadOptionalListElement<ExternalSheetName>("sheetNames", "sheetName"));
                ExternalDefinedNames.AddRange(c.ReadOptionalListElement<ExternalDefinedName>("tableDefinedNames",
                                                                                             "definedName"));
                SheetDataSet.AddRange(c.ReadOptionalListElement<ExternalSheetData>("sheetDataSet", "sheetData"));
                foreach (ExternalSheetName n in SheetNames)
                {
                    var sh = new ExternalSheet(this, n.Value);
                    Sheets.Add(sh);
                }
                using (this.CreateUndoManagerDisabler())
                {
                    foreach (ExternalSheetData data in SheetDataSet)
                    {
                        var sheet = (ExternalSheet) Sheets[data.SheetId];
                        sheet.GetData(data);
                    }
                }
                /* foreach (PackageRelationship rr in c.Part.GetRelationships())
                {
                    externalUri = rr.TargetUri;
                    relType = rr.RelationshipType;
                    Workbook currentWorkbook = c.GetData<Workbook>();
                    string targetFileName = Path.Combine(Path.GetDirectoryName(currentWorkbook.Document.FileName), rr.TargetUri.ToString());
                    if (!File.Exists(targetFileName))
                        continue;
                    SpreadsheetDocument doc = SpreadsheetDocument.Open(targetFileName, FileMode.Open, FileAccess.Read);

                    _workbook = doc.Workbook;
                    _workbook.SetParentWorkbook(this);
                }*/
            }
        }

        void IOfficeXmlSerializable.WriteXml(WriteContext context)
        {
            using (WriteContext c = context.Write("externalBook"))
            {
                string s = Uri.EscapeUriString(Document.FileName);
                s = Document.FileName;
                s = s.Replace(" ", "%20");
                s = s.Replace("{", "%7b");
                s = s.Replace("{", "%7b");
                s = s.Replace("}", "%7d");

                //file:///F:/WINDOWS/Application%20Data/MSN6/UserData/{4E4FDE80-C7F4-01C2-0200-00004CD745DE}/Hotmail/Temporary%20Mail%20Files%20(2A04B40A)/field%20schedules%20w%20unique%20games%20503.xls
                //file:///F:/WINDOWS/Application%20Data/MSN6/UserData/{4E4FDE80-C7F4-01C2-0200-00004CD745DE}/Hotmail/Temporary%20Mail%20Files%20(2A04B40A)/field%20schedules%20w%20unique%20games%20503.xls
                // file:///F:\WINDOWS\Application%20Data\MSN6\UserData\%7b4E4FDE80-C7F4-01C2-0200-00004CD745DE%7d\Hotmail\Temporary%20Mail%20Files%20(2A04B40A)\field%20schedules%20w%20unique%20games%20503.xls
                PackageRelationship r = context.Part.CreateRelationship(new Uri(s, UriKind.RelativeOrAbsolute),
                                                                        TargetMode.External,
                                                                        SpreadsheetConstants.
                                                                            ExternalLinkRelationshipPathType);
                    //\\ missing?
                c.SetString(OfficeConstants.RelationshipNamespace + "id", r.Id);
                c.WriteOptionalElementList(SheetNames, "sheetNames");
                c.WriteOptionalElementList(ExternalDefinedNames, "tableDefinedNames");
                c.WriteOptionalElementList(SheetDataSet, "sheetDataSet");
            }
        }

        #endregion
    }
}